package al.xc.common.util;

/**
 * Token 加解密
 */
public class TokenUtils {
    /**
     * 加密
     * @param str
     * @param vl
     * @return
     */
    public static String encryToken(String str, Integer... vl) {
        String md5 = CommonUtils.md5(str).toUpperCase();

        String[] vlHex = new String[vl.length];
        for (int i = 0; i < vl.length; ++i) {
            vlHex[i] = String.format("%08X", vl[i]);
        }
        StringBuilder result = new StringBuilder();
        result.append(md5, 0, 8);
        for (int i = 0;i < 8; ++i) {
            int index = ((int)(md5.charAt(i)) % 4);
            result.append(md5, 8 + i * 3, 8 + i * 3 + index);
            for (int j = 0; j < vl.length; ++j) {
                result.append(vlHex[j].charAt(i));
            }
            result.append(md5, 8 + i * 3 + index, 8 + i * 3 + index + 3 - index);
        }
        return result.toString().toUpperCase();
    }

    /**
     * 解密token
     * @param token
     * @return
     */
    public static Integer[] decryptToken(String token) {
        if (null == token || token.length() < 32) return null;
        if (0 != (token.length() - 32) % 8) return null;
        int vlNum = (token.length() - 32) / 8;
        StringBuilder[] vlHexBuild = new StringBuilder[vlNum];
        for (int i = 0;i < vlNum; ++i) {
            vlHexBuild[i] = new StringBuilder(8);
        }
        for (int i = 0; i < 8; ++i) {
            int index = ((int)token.charAt(i)) % 4;
            for (int j = 0;j < vlNum; ++j) {
                vlHexBuild[j].append(token.charAt(8 + i * (3 + vlNum) + index + j));
            }
        }
        try {
            Integer[] result = new Integer[vlNum];
            for (int i = 0;i < vlNum; ++i) {
                result[i] = Integer.parseInt(vlHexBuild[i].toString(), 16);
            }
            return result;
        } catch (Exception ex) {
            return null;
        }
    }
}
